package libretto.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.security.auth.login.LoginException;

import libretto.connection.ConnectionManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class Utils {

	public static final String TAG = Utils.class.getName();
	public static final String target_libretto = "https://univr.esse3.cineca.it/auth/studente/Libretto/LibrettoHome.do";
	public static final String target_info = "https://univr.esse3.cineca.it/auth/Home.do";

	// Riceve l'input stream della pagina e lo converte in stringa
	public static String inputStreamToString(InputStream is) {
		String line = "";
		BufferedReader in = null;

		StringBuilder sb = new StringBuilder(line);
		String NL = System.getProperty("line.separator");
		try {
			in = new BufferedReader(new InputStreamReader(is), 8 * 1024);
			while ((line = in.readLine()) != null) {
				sb.append(line).append(NL);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					Log.e(TAG, "Errore durante il rilascio della connessione.");
				}
			}
		}

		return sb.toString();
	}

	public static KeyStore loadTrustFile() throws KeyStoreException,
			NoSuchAlgorithmException, CertificateException, IOException {
		File sd = Environment.getExternalStorageDirectory();
		File file = new File(sd, "univr.esse3.cineca.it");
		KeyStore trustStore = KeyStore.getInstance("BKS");

		FileInputStream instream = null;
		try {
			instream = new FileInputStream(file);
			trustStore.load(instream, "changeit".toCharArray());
		} catch (Exception e) {
			Log.i(TAG, "Trustore inesistente.");
			trustStore.load(null);
		} finally {
			if (instream != null) {
				try {
					instream.close();
				} catch (IOException e) {
					Log.e(TAG, "Chiusura file non riuscita.");
				}
			}
		}
		return trustStore;
	}

	public static boolean isLink(String link) {
		Pattern pattern = Pattern.compile("(http|https)\\://(.*?)");
		Matcher matcher = pattern.matcher(link);
		return matcher.matches();
	}

	public static String removeSpecialString(String page_HTML, String regex) {
		// ELIMINO STRINGHE SPECIALI
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(page_HTML);
		while (matcher.find()) {
			page_HTML = matcher.replaceAll("");
		}
		return page_HTML;
	}

	public static String colorToHex(int r, int g, int b) {
		String colorstr = new String("#");
		// Red
		String str = Integer.toHexString(r);
		if (str.length() > 2) {
			str = str.substring(0, 2);
		} else if (str.length() < 2) {
			colorstr += "0" + str;
		} else {
			colorstr += str;
		}
		// Green
		str = Integer.toHexString(g);
		if (str.length() > 2) {
			str = str.substring(0, 2);
		} else if (str.length() < 2) {
			colorstr += "0" + str;
		} else {
			colorstr += str;
		}
		// Blue
		str = Integer.toHexString(b);
		if (str.length() > 2) {
			str = str.substring(0, 2);
		} else if (str.length() < 2) {
			colorstr += "0" + str;
		} else {
			colorstr += str;
		}
		return colorstr;
	}

	/**
	 * @param numero
	 * @param nCifreDecimali
	 * @return
	 */
	public static double arrotonda(double numero, int nCifreDecimali) {
		return Math.round(numero * Math.pow(10, nCifreDecimali))
				/ Math.pow(10, nCifreDecimali);
	}

	public static Bitmap downloadBitmap(String fileUrl) {
		InputStream is = null;

		if (!isLink(fileUrl))
			return null;
		try {
			ConnectionManager.getInstance().getEsse3Connection().get(fileUrl);
			is = ConnectionManager.getInstance().getEsse3Connection()
					.getEntity().getContent();
			return BitmapFactory.decodeStream(is);
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		} catch (IllegalStateException e) {
			Log.e(TAG, e.getMessage());
		} catch (LoginException e) {
			Log.e(TAG, e.getMessage());
		} finally {
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
				}
		}
		return null;
	}
}
